package com.technology.education.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;


import com.technology.education.MyApplication;
import com.technology.education.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by rocket on 2018/9/13 15:36.
 */
public class MediaUtils {
    private static MediaPlayer mPlayer;
    private static boolean isPause = false;

    public static MediaPlayer getMediaPlayer() {
        return mPlayer;
    }

    public static void playSound(Context context) {
        if (mPlayer == null) {
            mPlayer = new MediaPlayer();
            mPlayer.setLooping(true);

        } else {
            mPlayer.reset();
        }
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mPlayer.reset();
                return false;
            }
        });
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (mp.isLooping()) {
                    mp.start();
                }
            }
        });
        try {
            mPlayer.setLooping(true);
            mPlayer = MediaPlayer.create(context, R.raw.avchat_ring);
            mPlayer.prepare();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException("读取文件异常：" + e.getMessage());
        }
        mPlayer.start();
        if (!mPlayer.isLooping()) {
            mPlayer.setLooping(true);
        }
        isPause = false;
    }

    public static void pause() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.pause();
            isPause = true;
        }
    }

    // 继续
    public static void resume() {
        if (mPlayer != null && isPause) {
            mPlayer.start();
            isPause = false;
        }
    }

    public static void release() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    public static void stop() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }


    //应用安装路径下的"FileSave"文件夹
    private static final String DIR_AVIC_STAFF = MyApplication.Companion.getContext()
            .getExternalFilesDir("FileSave") + File.separator;

    //获取AvicStaff文件夹
    public static String getDirAvicStaff() {

        File fileDirRoot = new File(DIR_AVIC_STAFF);
        if (fileDirRoot.exists() && fileDirRoot.isDirectory()) return fileDirRoot.getAbsolutePath();
        else {

            boolean bCreateResult = fileDirRoot.mkdirs();
            if (bCreateResult) return fileDirRoot.getAbsolutePath();
            else {
                //二次创建
                boolean bCreateTwice = fileDirRoot.mkdirs();
                return bCreateTwice ? fileDirRoot.getAbsolutePath() : null;
            }
        }
    }

    /**
     * 根据uri获取路径
     *
     * @param uri 原始uri
     */
    public static String getFilePathFromUri(Context context, Uri uri) {
        if (uri == null) {
            return "";
        }
        switch (uri.getScheme()) {
            case "content":
                return getFileFromContentUri(context, uri);
            case "file":
                return uri.getPath();
            default:
                return "";
        }
    }

    /**
     * 根据Uri获取路径
     *
     * @param contentUri 输入的uri
     */
    private static String getFileFromContentUri(Context context, Uri contentUri) {

        if (contentUri == null) {
            return null;
        }
        File file;
        String filePath = "";
        String fileName;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME};
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(contentUri, filePathColumn, null,
                null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(filePathColumn[0]);
            //这里有可能为空 所以要做判断
            if (index > -1) {
                filePath = cursor.getString(index);
            }

            fileName = cursor.getString(cursor.getColumnIndex(filePathColumn[1]));
            cursor.close();

            if (!TextUtils.isEmpty(filePath)) {
                file = new File(filePath);
                if (!file.exists() || file.length() <= 0) {
                    filePath = getPathFromInputStreamUri(context, contentUri, fileName);
                }
            } else {
                filePath = getPathFromInputStreamUri(context, contentUri, fileName);
            }
        }
        return filePath;
    }

    /**
     * 用流拷贝文件一份到自己APP目录下
     */
    private static String getPathFromInputStreamUri(Context context, Uri uri, String fileName) {
        InputStream inputStream = null;
        String filePath = null;

        if (uri.getAuthority() != null) {
            try {
                inputStream = context.getContentResolver().openInputStream(uri);
                File file = createTemporalFileFrom(inputStream, fileName);
                filePath = file.getPath();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return filePath;
    }

    /**
     * 将文件通过流的方式复制到临时文件夹
     */
    private static File createTemporalFileFrom(InputStream inputStream, String fileName)
            throws IOException {
        File targetFile = null;

        if (inputStream != null) {
            int read;
            byte[] buffer = new byte[8 * 1024];
            //自己定义拷贝文件路径
            targetFile = new File(getDirAvicStaff(), fileName);
            if (targetFile.exists()) {
                boolean bDel = targetFile.delete();
                if (!bDel) targetFile.delete();
            }
            OutputStream outputStream = new FileOutputStream(targetFile);

            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            outputStream.flush();

            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetFile;
    }

}
